package recursos;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class LeerExcel {

	public LeerExcel() {

	}

	@SuppressWarnings("rawtypes")
	public static ArrayList LeerExcel(File file) {
		ArrayList datos = new ArrayList();
		try {
			Workbook workbook = WorkbookFactory
					.create(new FileInputStream(file));
			Sheet sheet = workbook.getSheetAt(0);
			for (int j = 1; j <= sheet.getLastRowNum(); j++) {
				Row row = sheet.getRow(j);
				ArrayList fila = new ArrayList();
				fila.add(j + " ");
				for (int i = 0; i < row.getLastCellNum(); i++) {
					Cell c = row.getCell(i);
					if (c != null) {
						c.setCellType(Cell.CELL_TYPE_STRING);
						fila.add(c.getStringCellValue());
					} else {
						fila.add(" ");
					}
				}
				datos.add(fila);
			}
		} catch (Exception e) {
			Sesion.mensajeError(null, "Mensaje: " + e.getMessage()
					+ "\nCausa: " + e.getCause());
		}
		return datos;
	}

	public LeerExcel(File file, DefaultTableModel dtm) {
		try {
			Workbook workbook = WorkbookFactory
					.create(new FileInputStream(file));
			Sheet sheet = workbook.getSheetAt(0);
			for (int j = 1; j <= sheet.getLastRowNum(); j++) {
				Row row = sheet.getRow(j);
				if (row != null) {
					if (row.getLastCellNum() > -1) {
						if (!row.getCell(row.getLastCellNum()-1).getStringCellValue().trim().equals("")) {
							Object[] fila = new Object[40];
							fila[0] = j;
							for (int i = 0; i < row.getLastCellNum(); i++) {
								Cell c = row.getCell(i);
								if (c != null) {
									c.setCellType(Cell.CELL_TYPE_STRING);
									fila[i + 1] = c.getStringCellValue();
								} else {
									fila[i + 1] = " ";
								}
							}
							dtm.addRow(fila);
						}
					}
				}
			}
		} catch (Exception e) {
			Sesion.mensajeError(null, "Mensaje: " + e.getMessage()
					+ "\nCausa: " + e.getCause());
		}
	}
	

}
